package com.cell.utils;

import com.cell.dao.UserDao;
import com.cell.entity.User;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.Random;

@Component
@ComponentScan
public class SMS {
    @Value("${sms.secretID}")
    private String secretID ;

    @Value("${sms.secretKey}")
    private String secretKey ;

    @Value("${sms.appID}")
    private String appID;

    @Value("${sms.signName}")
    String signName;

    @Value("${sms.templateID}")
    private String templateID;

    @Autowired
    UserDao userDao;

    public void sendSMS(User user, String validTime){
        System.out.println(signName);
        Random random = new Random();
        String validCode=String.valueOf(random.nextInt() * 10000).substring(1, 5);
        user.setValidCode(validCode);
        userDao.updateById(user);

        try{
            // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
            Credential cred = new Credential(secretID, secretKey);

            HttpProfile httpProfile = new HttpProfile();

            //实例化一个客户端配置对象,这个配置可以进行签名（使用私钥进行加密的过程），对方可以利用公钥进行解密
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-guangzhou");
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86"+user.getPhone()};
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId(appID);
            req.setSignName(signName);
            req.setTemplateId(templateID);

            String[] templateParamSet1 = {validCode, validTime};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例，与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }

    }

}
